<?php
/**
 * 平台产品
 * User: bgl
 * Date: 2022/9/7
 * Time: 15:10
 */

namespace App\Admin\Controllers\Products;


use App\Admin\Ajax\Products\ShopifySkuAjax;
use App\Admin\Controllers\ErpController;
use App\Models\Basics\ShopifyAccount;
use App\Models\Basics\SysCountry;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductShopifySku;
use App\Models\Product\ProductShopifySkuCCS;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;

class ShopifySkuController extends ErpController{

    protected $title = 'Shopify产品管理';

    protected $filters = [
        'seller_sku' => null,
        'sku' => null,
        'classify_id' => null,
        'season' => null,
        'country_id' => null,
        'seller_id' => null,
        'account_id' => null,
        'barcode_type' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['seller_sku'] = $this->filters['seller_sku'];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $filtersBlade['country_id'] = getOptions(SysCountry::options(),$this->filters['country_id']);
        $filtersBlade['seller_id'] = getOptions(User::getSellerOptions(FALSE),$this->filters['seller_id']);
        $filtersBlade['account_id'] = getOptions(ShopifyAccount::options(),$this->filters['account_id']);
        $filtersBlade['barcode_type'] = getOptions(ProductShopifySku::$_barcodeType,$this->filters['barcode_type']);
        $filtersBlade['status'] = getOptions(ProductShopifySku::$_status,$this->filters['status']);

        $downloadUrl = $this->getDownloadUrl('/xqc/products/shopify-sku-download');

        return view('products.shopify-sku.list.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _initQuery($filters){
        $query = ProductShopifySku::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;

            if($field == 'seller_sku'){
                $query->where(function ($query) use($filter){
                    $query->where('seller_sku', 'like', "%{$filter}%");
                });
            }
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }
            if($field == 'season'){
                $query->whereHas('skuClassify', function ($query) use($filter) {
                    $query->where('season',$filter);
                });
            }

            if(in_array($field,['country_id','seller_id','account_id','barcode_type','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    public function ajax(){
        $ajax = new ShopifySkuAjax();
        return $this->callAjax($ajax);
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['平台SKU','SKU','名称','季节性','品类','账号','国家','销售员','条码类型','条码','创建人','创建时间','启用'];
        RExcel::exportCsv('平台产品', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = ProductShopifySku::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    protected function form()
    {
        $form = new Form(new ProductShopifySku());

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->hidden('id');
        $form->text('seller_sku', '平台SKU')->rules('required')->required()->setWidth(5);
        $form->select('account_id', '账号')->options(ShopifyAccount::options(['status' => 1]))->required()->setWidth(5);
        $form->select('country_id', '国家')->options(SysCountry::options())->required()->rules("required")->setWidth(5);
        $form->select('psku_id', 'SKU')
            ->options(function ($id) {
                $id = $id ?: old('psku_id');
                $ps = ProductSku::getModelById($id);
                if ($ps) {
                    return [$ps->id => $ps->psku_code];
                }else{
                    return [];
                }
            })->ajax('/xqc/api-sys/products-vague-sku')
            ->rules('required')->required()->setWidth(5);
        $form->select('barcode_type', '条码类型')->options(ProductShopifySku::$_barcodeType)->required()->rules("required")->setWidth(5);
        $form->text('barcode', '条码')->rules('required_if:barcode_type,1,2', ['required_if'=>'请录入条码'])->setWidth(5);
        $form->radio('status', '启用')->options(ProductShopifySku::$_status)->default(1)->setWidth(5);
        $form->hidden('cuser_id')->value(Admin::user()->id);
        $form->hidden('seller_id');

        if($form->isCreating()){
            $form->disableCreatingCheck(false);
        }
        $form->saving(function (Form $form) {
            // 判断是否是新增操作
            if ($form->isCreating()) {
                if($form->barcode_type == 3){
                    $form->barcode = '无';
                }

                //更新,回写品类销售
                $classify_id = ProductSku::getValueById($form->psku_id, 'classify_id');
                $ccs = ProductShopifySkuCCS::returnSellerId($form->country_id, $classify_id, Admin::user()->id);
                $form->seller_id = $ccs->seller_id;

                $count = ProductShopifySku::query()
                    ->where('seller_sku',$form->seller_sku)
                    ->where('country_id',$form->country_id)
                    ->count();
                if($count > 0){
                    admin_error('重复添加','该平台下的平台SKU+国家已存在');
                    return back()->withInput();
                }
            }else{
                if($form->barcode_type == 3){
                    $form->barcode = '无';
                }

                //更新,回写品类销售
                if(($form->country_id != $form->model()->country_id)||($form->psku_id != $form->model()->psku_id)){
                    $classify_id = ProductSku::getValueById($form->psku_id, 'classify_id');
                    $ccs = ProductShopifySkuCCS::returnSellerId($form->country_id, $classify_id, Admin::user()->id);
                    $form->seller_id = $ccs->seller_id;
                }

                $count = ProductShopifySku::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('seller_sku', $form->seller_sku)
                    ->where('country_id', $form->country_id)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该平台下的平台SKU+国家已存在');
                    return back()->withInput();
                }
            }
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });
        return $form;
    }

}
